<template>
  <div class="flex min-h-screen bg-gray-100">
    <div class="flex-1 bg-cover bg-center" style="background-image: url('https://picsum.photos/1200/800');">
      <!-- 这里可以添加一些宣传文案或者图片 -->
    </div>
    <div class="w-1/3 bg-white flex flex-col justify-center items-center p-8">
      <h1 class="text-4xl font-extrabold text-gray-800 mb-8 text-center tracking-wide">电商后台管理系统登录</h1>
      <div class="w-full max-w-md">
        <el-form ref="loginFormRef" :model="loginForm" label-width="80px">
          <el-form-item label="用户名">
            <el-input v-model="loginForm.username" placeholder="请输入用户名" class="custom-input" size="default" />
          </el-form-item>
          <el-form-item label="密码">
            <el-input v-model="loginForm.password" type="password" placeholder="请输入密码" class="custom-input" size="default" />
          </el-form-item>
          <el-form-item>
            <p v-if="errorMessage" class="error-message">{{ errorMessage }}</p>
          </el-form-item>
          <el-form-item>
            <el-button @click="handleLogin" type="primary" class="w-full">登录</el-button>
          </el-form-item>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue';
import axiosInstance from '../axiosInstance';
import { useRouter } from 'vue-router';

const loginFormRef = ref(null);
const loginForm = ref({
  username: '',
  password: ''
});
const router = useRouter();
const errorMessage = ref('');

const handleLogin = async () => {
  if (!loginForm.value.username) {
    errorMessage.value = '请输入用户名';
    return;
  }
  if (!loginForm.value.password) {
    errorMessage.value = '请输入密码';
    return;
  }
  try {
    const response = await axiosInstance.post('/admin/login', loginForm.value);
    if (response.data.code === '200') {
      const authorization = response.data.data;
      localStorage.setItem('Authorization', authorization);
      router.push('/Main');
      errorMessage.value = '';
    } else {
      errorMessage.value = response.data.message;
    }
  } catch (error) {
    console.error(error);
    errorMessage.value = '登录失败，请稍后重试';
  }
};
</script>

<style scoped>
.error-message {
  color: red;
}

:deep(.custom-input) {
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  transition: all 0.3s;
  &:hover {
    border-color: #c0c4cc;
  }
  &:focus {
    border-color: #409EFF;
    outline: none;
    box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
  }
}
</style>